//
//  i18nViewController.m
//  i18n
//
//  Created by Patrick De Caluwe on 10/2/11.
//  Copyright 2011 patrick.decaluwe@student.uclouvain.be. All rights reserved.
//

#import "i18nViewController.h"
#import "filesystem.h"


@implementation i18nViewController


@synthesize scrollView;
@synthesize difficultWordsTableView;

@synthesize questionLabel;

@synthesize homeButton;
@synthesize answerButton1;
@synthesize answerButton2;
@synthesize answerButton3;

@synthesize correctLabel1;
@synthesize correctLabel2;
@synthesize correctLabel3;


@synthesize currentWord;
@synthesize numberOfWords;
@synthesize listOfWords;
@synthesize listOfDifficultWords;

@synthesize currentAnswerInt;

filesystem *fs;

NSString *currentQuestion;
NSString *currentAnswer;
NSString *fakeAnswer1;
NSString *fakeAnswer2;


NSMutableArray *texts;
NSMutableArray *meanings;

-(void) nextRound
{
    currentQuestion = [[listOfWords objectAtIndex:0] objectAtIndex: currentWord];
    currentAnswer = [[listOfWords objectAtIndex:1] objectAtIndex: currentWord];
    
    [questionLabel setText:currentQuestion];
  
    int i1,i2 = currentWord;
    
    while(i1 == i2 || i1 == currentWord ||i2 == currentWord)
    {
    i1 = arc4random() % numberOfWords;
    i2 = arc4random() % numberOfWords;
    }
    NSLog(@"i1: %i i2: %i", i1, i2);
    fakeAnswer1 = [[listOfWords objectAtIndex:1] objectAtIndex: i1];
    fakeAnswer2 = [[listOfWords objectAtIndex:1] objectAtIndex: i2];
   
    currentAnswerInt = arc4random() % 3;

    switch (currentAnswerInt) 
    {
        case 0:
            [answerButton1 setTitle:currentAnswer forState:UIControlStateNormal];
            [answerButton2 setTitle:fakeAnswer1 forState:UIControlStateNormal];
            [answerButton3 setTitle:fakeAnswer2 forState:UIControlStateNormal];
            break;
        case 1:
            [answerButton1 setTitle:fakeAnswer1 forState:UIControlStateNormal];
            [answerButton2 setTitle:currentAnswer forState:UIControlStateNormal];
            [answerButton3 setTitle:fakeAnswer2 forState:UIControlStateNormal];
            break;
        case 2:
            [answerButton1 setTitle:fakeAnswer1 forState:UIControlStateNormal];
            [answerButton2 setTitle:fakeAnswer2 forState:UIControlStateNormal];
            [answerButton3 setTitle:currentAnswer forState:UIControlStateNormal];
            break;
    }
    

    NSLog(@"***********************");
    int i;
    NSLog (@"Printing the %i words ",numberOfWords);
    for (i = 0; i < numberOfWords; i++)
    {
        NSLog(@"--------------------------");
        NSLog (@"Word = %@", [[listOfWords objectAtIndex: 0] objectAtIndex:i] );
        NSLog (@"Meaning = %@", [[listOfWords objectAtIndex: 1] objectAtIndex:i] );    
    }
    currentWord++;
    
    if (currentWord==numberOfWords)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"List Completed" message:@"You have now met all the words of this list once"
                                                       delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        [alert release];
        currentWord = 0;
    }
    
}

-(IBAction)homeButtonClicked:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}


-(IBAction)answerClicked:(id)sender
{
    [correctLabel1 setText:@" "];
    [correctLabel2 setText:@" "];
    [correctLabel3 setText:@" "];
    
    NSString *message =@"False";
    
    if(currentAnswerInt == [sender tag])
    {
        message = @"Correct!";
    }   
        
    switch([sender tag])
    {
        case 0 :  
            [correctLabel1 setText:message];
            break;
        case 1 :
            [correctLabel2 setText:message];
            break;
        case 2 :
            [correctLabel3 setText:message];
            break;                        
    }
     
    
    
    [self nextRound];
}

-(IBAction)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath:(id)sender
{
    NSLog(@"oufti");
    NSString *wordSelected = [listOfWords objectAtIndex:indexPath.row];
    NSString *msg = [NSString stringWithFormat:@"You have selected %@",wordSelected];
    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Word Selected"
                                                   message:msg
                                                  delegate:self
                                         cancelButtonTitle:@"Cancel"
                                         otherButtonTitles:nil];
    [alert show];
    [alert release];
}


- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:SimpleTableIdentifier] autorelease];
    }
    NSUInteger row = [indexPath row];
    cell.textLabel.text = [listOfDifficultWords objectAtIndex:row];
    return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"arrive ici");
    NSLog(@"objet 3 dans list of dif words : %@",[listOfDifficultWords objectAtIndex:3]);
    NSLog(@"le count du table view %i",[listOfDifficultWords count]);
    return [listOfDifficultWords count];
}


-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"Difficult Words";
}
   

- (void)parseXMLFile:(NSString *)pathToFile {
    BOOL success;
    NSURL *xmlURL = [NSURL fileURLWithPath:pathToFile];

    if(xmlParser) {[xmlParser release];}
    xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
    [xmlParser setDelegate:self];
    [xmlParser setShouldResolveExternalEntities:YES];
    success = [xmlParser parse]; // return value not used
    // if not successful, delegate is informed of error
}

- (void) parser: (NSXMLParser *)parser 
didStartElement:(NSString *)elementName
   namespaceURI:(NSString *)namespaceURI
  qualifiedName:(NSString *)qName
     attributes:(NSDictionary *)attributeDict 
{
    if ( [elementName isEqualToString:@"word"]) 
    {
        // words is an NSMutableArray instance variable
        if (!words)
            words = [[NSMutableString alloc] init];
        
        wordFound = TRUE;
        numberOfWords = numberOfWords+1;
        NSLog(@" number Of words : %i",numberOfWords);
        NSLog(@"entered words tag");
                
        currentQuestion = [attributeDict objectForKey:@"text"];
        [[listOfWords objectAtIndex:0] addObject:currentQuestion];        
        NSLog(@" Question found : %@",currentQuestion);
        

        currentAnswer = [attributeDict objectForKey:@"meaning"];
        [[listOfWords objectAtIndex:1] addObject:currentAnswer];
        NSLog(@"Meaning found : %@",currentAnswer);
        
        return;
    }
    
    
    if ( [elementName isEqualToString:@"word"]) 
    {
        // words is an NSMutableArray instance variable
        return;
    }
}   

- (void) parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string 
{
    if(wordFound)
    [words appendString:string];
}


- (void)parser:(NSXMLParser *)parser 
 didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI 
 qualifiedName:(NSString *)qName {
    // ignore root and empty elements
    if (( [elementName isEqualToString:@"addresses"]) ||
        ( [elementName isEqualToString:@"address"] )) return;
    
    if ( [elementName isEqualToString:@"words"] ) {
        // addresses and currentPerson are instance variables

        NSLog(@"%@", words);        // ... here ABMultiValue objects are dealt with ..
        wordFound=FALSE;
   return;
    }
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    /*--- FileSystem ---*/
    fs = [[filesystem alloc] init];

    //--- add items to words array --- 
    NSString * filename = [[fs documentsPath] stringByAppendingPathComponent:@"ivocatest.xml"];
    NSLog(@"file to be parsed : %@",filename);
    
    currentWord = 0;
    numberOfWords = 0;
    NSLog(@"number of words : %i", numberOfWords);

    texts = [[NSMutableArray alloc] init];
    meanings = [[NSMutableArray alloc] init];
    
    self.listOfWords = [[NSMutableArray alloc ] initWithCapacity:2 ];

    [listOfWords addObject:texts];
    [listOfWords addObject:meanings]; 
    [self parseXMLFile:filename];
        
    listOfDifficultWords = [[NSMutableArray alloc] initWithArray:texts];
    NSLog(@"-adfjafjaopdsfojajopfdadopfaopjd, %@",listOfDifficultWords);
    
        
    [self nextRound];
    NSLog(@"-adfjafjaopdsfojajopfdadopfaopjd");
    [super viewDidLoad];  
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
